package demo.feign;

import feign.Client;
import feign.Contract;
import feign.Feign;
import feign.Feign.Builder;
import feign.auth.BasicAuthRequestInterceptor;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.openfeign.FeignBuilderCustomizer;
import org.springframework.cloud.openfeign.FeignClientBuilder;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @author: lin
 * @time: 2024/7/30 10:33
 */
@Component
public class FeignBuilder implements ApplicationContextAware, ApplicationRunner {


    private ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {

        FeignClientBuilder feignClientBuilder = new FeignClientBuilder(applicationContext);
        OrderService orderClient = feignClientBuilder.forType(OrderService.class, "order").url("http://localhost:8023/order")
                .contextId("order1").fallback(
                        OrderFallBack.class).customize(builder -> builder.requestInterceptor(new FeignUrlInterceptor())).build();

        System.out.println(orderClient.deduct(2));

        OrderService orderClient2 = feignClientBuilder.forType(OrderService.class, "order").url("http://localhost:8023/order")
                .contextId("order2").build();
        System.out.println(orderClient2.deduct(3));

//        ConfigurableListableBeanFactory beanFactory = (ConfigurableListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
//        beanFactory.registerSingleton("orderClient", orderClient);
//        OrderService bean = applicationContext.getBean(OrderService.class);
//        System.out.println(bean);
    }
}
